package com.allen.mk.admin.springsecurity.config;


import com.allen.mk.admin.springsecurity.handler.*;
import com.allen.mk.admin.springsecurity.jwtfilter.JWTAuthenticationTokenFilter;
import com.allen.mk.admin.springsecurity.provider.UserAuthenticationProvider;
import com.allen.mk.admin.util.GeneralConstant;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import org.springframework.security.web.SecurityFilterChain;


import javax.annotation.Resource;


/**
 * SpringSecurity配置类
 * @Author Allem
 * @CreateTime 2024/4/3 10:55
 */

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig implements GeneralConstant {

    @Resource
    private UserAuthenticationEntryPointHandler userAuthenticationEntryPointHandler;

    @Resource
    private UserLoginSuccessHandler userLoginSuccessHandler;

    @Resource
    private UserLoginFailureHandler userLoginFailureHandler;

    @Resource
    private UserLogoutSuccessHandler userLogoutSuccessHandler;

    @Resource
    private UserAuthAccessDeniedHandler userAuthAccessDeniedHandler;


    @Resource
    private UserAuthenticationProvider authenticationProvider;



    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{

        http.
                authorizeRequests().antMatchers("/eb-system-admin").permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginProcessingUrl("/user/login").permitAll().successHandler(userLoginSuccessHandler)
                .failureHandler(userLoginFailureHandler)
                .and().logout().logoutUrl("/user/logout").logoutSuccessHandler(userLogoutSuccessHandler)
                .and().exceptionHandling().authenticationEntryPoint(userAuthenticationEntryPointHandler).accessDeniedHandler(userAuthAccessDeniedHandler)
                .and().authenticationProvider(authenticationProvider)
                .addFilter(new JWTAuthenticationTokenFilter(authentication -> authentication)).csrf().disable().cors();
        return http.build();
    }

}
